import { Component } from "@angular/core";
import { NavController,App,AlertController,LoadingController } from 'ionic-angular';

import { AppConfig } from '../../app/app.config';

import { ImagePicker } from '@ionic-native/image-picker';
import { HttpClient,HttpHeaders } from '@angular/common/http';
import { FileTransfer,FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
import { NativeStorage } from '@ionic-native/native-storage'; 
import { TranslateService } from '@ngx-translate/core'

import { AboutusPage } from "../more/set/about/about";
@Component({
    selector: 'page-regist',
    templateUrl: 'regist.html',
})
export class RegistPage {
    info = {
        level:1,
        firstname: '',
        lastname: '',
        email: '',
        captcha: '',
        password: '',
        mobile: '',
        address: '',
        country: '',
        status: 0,
        gender: 1,
        avatar: '',
    }
    header={'background-image':'url(./assets/imgs/login_img.png)'};
    protocol: string;
    typepwd= 'password';
    verify_time = 0;
    loading:any;
    aboutusPage = AboutusPage
    constructor(
        private navCtrl: NavController,
        private app:App,
        private http: HttpClient,
        private alertCtrl: AlertController,
        private imgPicker:ImagePicker,
        private transfer:FileTransfer,
        private loadingCtrl:LoadingController,
        private storage:NativeStorage,
        private translate: TranslateService,
    ) {
        translate.setDefaultLang('en');
    }
    ionViewDidEnter(){
      this.storage.getItem('lang').then(res=>{
          this.translate.use(res)
      })
    }
    

    alertb(title,subTitle){
        let alert = this.alertCtrl.create({
            title: title,
            subTitle: subTitle,
            buttons: ['OK']
        });
        alert.present();
    }
    goRegister(){
        if(this.protocol){
            this.http.post(AppConfig.getUrl()+'login/register', this.info,{headers: new HttpHeaders({ 'Content-Type': 'application/json' }) })
                .subscribe( (res) => {
                    if(res['code']===101){
                        this.alertb('success','registration success,you can log in');
                        this.navCtrl.pop();
                    }else if(res['code']===202){
                        this.alertb('Error!',res['msg']);
                    }
                })
        }else{
            this.alertb('Error!','Please confirm check the platform agreement！');
        }
    }
    toggle(){
        let iconfont = document.querySelector('#signs')
        if(this.typepwd=='password'){
            this.typepwd = 'text'
            iconfont.classList.remove('icon-login_open')
            iconfont.classList.add('icon-login_close')
        }else{
            this.typepwd = 'password'
            iconfont.classList.remove('icon-login_close')
            iconfont.classList.add('icon-login_open')
        }
    }
    goCode(){
        if(this.verify_time===0){
            this.http.post(AppConfig.getUrl()+'tool/sendcaptcha?way=register', AppConfig.urlEcode({receiver:this.info.email}),{headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) })
            .subscribe( (res) => {
                if(res['code']===101){
                    this.alertb('success','send success,please wait');
                    this.verify_time = 60
                    let timer =setInterval(() => {
                        if(this.verify_time!==0){
                            this.verify_time--
                        }else{
                            clearInterval(timer)
                        }
                    }, 1000);
                }else if(res['code']===202){
                    this.alertb('Error!',res['msg']);
                }
            })
        }else{
            this.alertb('Error','Verification code has been sent, please try again later');
        }
        
    }
    loadWait(){
        this.loading = this.loadingCtrl.create({
            content: 'Please wait...'
        });
        this.loading.present();
    }
    imgSelect(){
        this.imgPicker.getPictures({maximumImagesCount:1}).then((results)=>{
            if(!!results.length){
                this.loadWait();
                for (var i=0;i<results.length;i++){
                    
                    let fileTransfer: FileTransferObject = this.transfer.create();
                    let options:FileUploadOptions = {
                        fileKey: 'img',
                        chunkedMode: false,
                     }
                    fileTransfer.upload(results[0], AppConfig.getUrl()+'login/upload_avatar',options,true).then((data) => {
                        let response = JSON.parse(data.response) 
                        if(response['code']==101){
                            this.header = {'background-image': 'url('+AppConfig.getMainUrl()+response['data']['thumb_img']+')'}
                            this.info.avatar = response['data']['thumb_img']
                        }else{
                            this.alertb('Upload failed','');
                        }
                        this.loading.dismiss();
                    }, (err) => {
                        this.alertb('Upload failed','');
                        this.loading.dismiss();
                    })
                }
            }
            
        })
    }
}